/*
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  Author: hakanai
 */

#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <libsdb.h>
#include <unistd.h>

#define TFILE "/tmp/oosaAest39ax.sdb"

struct s_record1_t {
  int num;
  char c;
};

static int simple_append_record() {
  sdb_t db;
  struct s_record1_t t = { 0 };

  t.num = 42;
  t.c = 'a';

  assert(sdb_open(TFILE, &db) == SDB_OK);
  assert(sdb_append(&db, &t, sizeof(t)) == SDB_OK);

  assert(sdb_size(&db) == 1);
  assert(sdb_append(&db, &t, sizeof(t)) == SDB_OK);
  assert(sdb_size(&db) == 2);

  for (int i = 3; i < 20; i++) {
    assert(sdb_append(&db, &t, sizeof(t)) == SDB_OK);
    assert(sdb_size(&db) == i);
  }

  sdb_close(&db);
  unlink(TFILE);

  return 0;
}

static int simple_read() {
  sdb_t db;
  struct s_record1_t t = { 0 }, b = { 0 };

  t.num = 29;
  t.c = 'F';

  unlink(TFILE);
  assert(sdb_open(TFILE, &db) == SDB_OK);
  assert(sdb_append(&db, &t, sizeof(t)) == SDB_OK);
  assert(sdb_size(&db) == 1);

  assert(sdb_append(&db, &t, sizeof(t)) == SDB_OK);
  assert(sdb_size(&db) == 2);

  assert(sdb_read(&db, 0, &b) == SDB_OK);

  assert(b.num == 29);
  assert(b.c == 'F');

  assert(sdb_read(&db, 1, &b) == SDB_OK);

  assert(b.num == 29);
  assert(b.c == 'F');

  sdb_close(&db);
  unlink(TFILE);

  return 0;
}

struct s_record2_t {
  uint32_t a;
  uint16_t b;
};

static int read_multiple() {
  sdb_t db;
  struct s_record2_t t = { 0 }, b = { 0 };

  unlink(TFILE);
  assert(sdb_open(TFILE, &db) == SDB_OK);

  for (int i = 0; i < 200; i++) {
    t.a = i;
    t.b = i + 2;
    assert(sdb_append(&db, &t, sizeof(struct s_record2_t)) == SDB_OK);
  }

  for (int i = 0; i < 200; i++) {
    assert(sdb_read(&db, i, &b) == SDB_OK);
    assert(b.a == i);
    assert(b.b == (i + 2));
  }

  sdb_close(&db);
  unlink(TFILE);
  return 0;
}

int main() {
  unlink(TFILE);
  assert(!simple_append_record());
  assert(!simple_read());
  assert(!read_multiple());
  return 0;
}

